import img1 from "../img/e.jpg"
import img2 from "../img/q.jpg"
import img3 from "../img/t.jpg"
import img4 from "../img/u.jpg"
const defaultData = {
    list:[],
    listChildren:[],
    allPrice:0,
    allCheck:false,
    urlData : [
        img1,
        img2,
        img3,
        img4
    ],
    shopCar:localStorage.getItem('shopCar')? JSON.parse(localStorage.getItem('shopCar')):[]
}

const reduce = (state = defaultData,{type,payload,}) => {
    let newState = JSON.parse(JSON.stringify(state))

    const calculatePrice = () =>{
        newState.allPrice = 0 
        newState.shopCar.forEach(item=>{
            if (item.checked) {
                newState.allPrice += item.price * item.count
            }
           
        })
    }
    switch (type) {
        case "ALLDATA":
            newState.list = payload
            newState.listChildren = payload[0].children
            return newState
            
        case "CHECKTAB":
            newState.listChildren = newState.list[payload].children
            return newState

        case "ADDSHOPCAR":
            newState.shopCar.push(payload)
            localStorage.setItem('shopCar',JSON.stringify(newState.shopCar) )
            return newState

        case "ADDCOUNT":
            const filterData = newState.shopCar.filter(item=>item.id === payload)
                console.log(filterData);
            filterData[0].count++
            newState.shopCar.forEach((item) => {
                if (item.id === filterData[0].id) {
                    item = filterData[0]
                }
            })
            calculatePrice()
            return newState

        case "DELCOUNT":
            let filterData1 = newState.shopCar.filter(item=>item.id === payload)
            filterData1[0].count--
            newState.shopCar.forEach((item) => {
                if (item.id === filterData1[0].id) {
                    item = filterData1[0]
                }
            })
            calculatePrice()
            return newState

        case "ONECHECKBOX":
            newState.shopCar[payload.index].checked = !newState.shopCar[payload.index].checked
            const flag = newState.shopCar.every((item) => {
                // debugger
                return item.checked
              
            })
            console.log(flag);
            newState.allCheck = flag
            calculatePrice()
            return newState
        
        case "AllCHECKBOX":
            newState.shopCar.forEach(item=>{
                item.checked = payload
            })
            calculatePrice()
            newState.allCheck = payload
            return newState
        case "DELITEM":
            newState.shopCar.splice(payload, 1)
            calculatePrice()
            return newState
        default:
           return newState
    }
}

export default reduce